package com.concurrence;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * CountForkAndJoinDemo.. 多线程计算
 *
 * @author Lizhong
 * @date 2019/4/9
 */
public class CountForkAndJoinDemo extends RecursiveTask<Integer> {
    private int threshold = 10;
    private int start;
    private int end;

    public CountForkAndJoinDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        CountForkAndJoinDemo countForkAndJoinDemo = new CountForkAndJoinDemo(1, 10000);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(countForkAndJoinDemo);
        System.out.println(submit.get());
        forkJoinPool.shutdown();
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean b = (end - start) > threshold;
        if (b) {
            int middle = (end + start) / 2;
            CountForkAndJoinDemo countForkAndJoinDemo = new CountForkAndJoinDemo(start, middle);
            CountForkAndJoinDemo countForkAndJoinDemo2 = new CountForkAndJoinDemo(middle + 1, end);

            countForkAndJoinDemo.fork();
            countForkAndJoinDemo2.fork();

            Integer sum1 = countForkAndJoinDemo.join();
            Integer sum2 = countForkAndJoinDemo2.join();
            sum = sum1 + sum2;
        } else {
            for (int i = start; start <= end; start++) {
                sum += start;
            }
        }
        return sum;
    }
}
